//
//  Person.swift
//  Center
//
//  Created by Flutter on 2021/8/5.
//

import Foundation
import RealmSwift
import Standard

// Define the enum
public enum Gender: Int, PersistableEnum {
    case male
    case female
}

public class Person: Object {
    @Persisted(primaryKey: true) public var _id: ObjectId
    @Persisted public var name: String = ""
    @Persisted public var avatar: String?
    @Persisted public var gender: Gender?
    @Persisted public var dateOfBirth: Date?
    @Persisted public var createdAt: Date = Date()
    @Persisted public var updatedAt: Date?
    @Persisted public var isDefault: Bool = false
    @Persisted public var eyeTestHistory: List<EyeTestInfo>
}

extension Person: TypeName {}

private extension Person {
    static let logger = Loggers[typeName]
    static let realm: Realm? =  {
        do {
            let realm = try Realm()
            return realm
        } catch {
            logger.error("\(error)")
            return nil
        }
    }()
}


public extension Person {
    
    /// 获取所有 Person
    static func getPeople() -> [Person]?{
        let users = realm?.objects(Person.self).toArray(type: Person.self)
        return users
    }
    
    /// 新增 Person
    @discardableResult
    func insert() -> Bool {
        self.createdAt = Date()
        guard let realm = Self.realm else { return false }
        do {
            try realm.write {
                realm.create(Person.self, value: self,update: .modified)
            }
            return true
        } catch {
            Self.logger.error("\(error)")
            return false
        }
    }
    
    /// 更新 Person 信息
    @discardableResult
    func update() -> Bool {
        self.updatedAt = Date()
        guard let realm = Self.realm else { return false }
        do {
            try realm.write {
                realm.add(self, update: .modified)
            }
            return true
        } catch {
            Self.logger.error("\(error)")
            return false
        }
    }
    
    /// 删除 Person
    @discardableResult
    func delete() -> Bool{
        guard let realm = Self.realm else { return false }
        do {
            try realm.write {
                realm.delete(self)
            }
            return false
        } catch {
            Self.logger.error("\(error)")
            return true
        }
    }
    
    
    /// Person 添加检查历史记录
    @discardableResult
    func addHistory(eyeTestInfo: EyeTestInfo) -> Bool {
        self.eyeTestHistory.append(eyeTestInfo)
        return self.update()
    }
    
}
